<?php


namespace App\Remote\Feishu;


use Closure;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Psr7\Utils;
use Illuminate\Http\Response;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpFoundation\Request as RequestAlias;

class FeishuImageRemote extends FeishuRemote
{

    const IMAGE_TYPE_MSG    = "message";
    const IMAGE_TYPE_AVATAR = "avatar";


    /**
     * 基础请求头构建
     *
     * @return array
     * @throws Exception
     */
    public static function buildBasicHeaders(): array
    {
        return [
            "Content-Type"  => "multipart/form-data",
            'Authorization' => FeishuAuthRemote::getInstance()->getAccessToken()
        ]; // TODO: Change the autogenerated stub
    }

    public static function registerResponseHandle(): Closure
    {
        return function () {
            list($responseHttpCode, $responseContents) = func_get_args();
            if ($responseHttpCode == Response::HTTP_OK && isJson($responseContents)) {
                $responseArr = jsonToArr($responseContents);
                if ($responseArr["code"] == 0) {
                    return $responseArr["data"];
                }
                throw new Exception($responseArr["msg"]);
            }
            throw new Exception(vsprintf("%s - %s", [$responseHttpCode, $responseContents]));
        };
        // TODO: Change the autogenerated stub
    }

    /**
     * @param string $file
     * @param string $msgType
     * @return mixed|void
     * @throws GuzzleException|ValidationException
     */
    public static function uploadImage(string $file, string $msgType = self::IMAGE_TYPE_MSG)
    {
        return self::customRequestV3(
            "/open-apis/im/v1/images",
            RequestAlias::METHOD_POST,
            [
                'multipart' => [
                    [
                        'name'     => 'image_type',
                        'contents' => $msgType
                    ],
                    [
                        'name'     => 'image',
                        'contents' => Utils::tryFopen($file, 'r'),
                        'filename' => $file,
                    ]
                ]
            ]
        );
    }


}
